package com.example.mypigcar.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.mypigcar.common.exception.RepeatRegisterException;
import com.example.mypigcar.pojo.dto.AddDriverLicenseDTO;
import com.example.mypigcar.utils.OSSUtils;
import com.example.mypigcar.common.core.R;
import com.example.mypigcar.common.core.SR;
import com.example.mypigcar.common.exception.InsufficientBalance;
import com.example.mypigcar.pojo.po.User;
import com.example.mypigcar.pojo.dto.LoginDTO;
import com.example.mypigcar.pojo.dto.UserBalanceDTO;
import com.example.mypigcar.pojo.dto.UserLicenseDTO;
import com.example.mypigcar.service.UserService;
import com.example.mypigcar.utils.DriverLicenseUtils;
import com.example.mypigcar.utils.JWTUtils;
import com.example.mypigcar.utils.UUIDUtils;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zkw
 * @createTime 2021年06月12日 20:44:00
 */
@Api(value = "用户controller", tags = {"用户操作接口"})
@RequestMapping("user")
@RestController
public class UserController {
    @Resource
    UserService userService;


    @ApiOperation("登录")
    @PostMapping("/login")
    public R login(
            @RequestBody @ApiParam(name = "用户对象", value = "传入json格式", required = true) LoginDTO user) {
        try {
            User loginUser = userService.getUser(user);
            Map<String, String> map = new HashMap<>();//用来存放payload
            map.put("userID", loginUser.getUserId() + "");
            map.put("username", loginUser.getUsername());
            String token = JWTUtils.getToken(map);
            return R.ok().data("token", token).data("user", loginUser);
        } catch (Exception e) {
            return R.error();
        }
    }

    @ApiOperation("测试是否登录")
    @PostMapping("/test")
    public R test(HttpServletRequest request) {
        String username = JWTUtils.getUsernameByToken(request);
        return R.ok().message(username);
    }

    @ApiOperation("修改用户信息")
    @PutMapping()
    public R updateUser(
            @RequestBody @ApiParam(name = "用户对象", value = "传入json格式", required = true) User user) {
        boolean b = userService.updateUser(user);
        return b ? R.ok() : R.error().message("更新失败");
    }

    @ApiOperation("修改用户余额")
    @PutMapping("/balance")
    public R updateUserBalance(@ApiParam("用户余额对象") @RequestBody UserBalanceDTO userBalance) {
        User user = new User();
        BeanUtils.copyProperties(userBalance, user);
        try {
            UserBalanceDTO userBalance1 = userService.updateUserBalance(user);
            return R.ok().data("result", userBalance1);
        } catch (InsufficientBalance e) {
            return R.error().message("余额不足");
        }
    }

    @ApiOperation("添加用户驾驶证")
    @PostMapping("/license")
    public SR addUserLicense(@ApiParam("用户驾驶证对象") @RequestBody UserLicenseDTO userLicenseDTO) {
        UserLicenseDTO userLicenseDTO1 = userService.saveUserLicense(userLicenseDTO);
        return SR.ok().data(userLicenseDTO1);
    }

    @ApiOperation("获取全部用户")
    @GetMapping("/all")
    public SR getAllUser() {
        List<User> all = userService.listUsers();
        return SR.ok().data(all);
    }

    @ApiOperation("根据账号查询用户")
    @GetMapping("/{username}")
    public SR getUserByName(@PathVariable("username") String username) {
        User user = userService.getUserByName(username);
        return SR.ok().data(user);
    }

//    @ApiOperation("解析驾驶证")
//    @GetMapping("license/parse")
//    public SR getDriverLicense(String imgUrl){
//        return SR.ok().data(DriverLicenseUtils.parseLicenseToObject(imgUrl));
//    }

    @ApiOperation("上传驾驶证正面")
    @PostMapping("/upload/license/front")
    public SR uploadLicense(MultipartFile file, HttpServletRequest request) {
        String userIdByToken = JWTUtils.getUserIdByToken(request);
        User user = new User();
        user.setUserId(Integer.parseInt(userIdByToken));
        try {
            System.out.println(file);
            String url = OSSUtils.uploadFile(UUIDUtils.getUUID().toString(), "user/license/", file);
            JSONObject jsonObject = DriverLicenseUtils.parseLicenseToObject(url);
            String num = (String) jsonObject.get("num");  //获取驾驶证号
            String name = (String) jsonObject.get("name");  //获取驾驶证号
            user.setName(name);          //更新姓名
            user.setLicense(num);        //更新驾驶证号
            user.setLicenseFront(url);   //更新驾驶证正面图片
            boolean result = userService.updateUser(user);
            return result ? SR.ok().data(url) : SR.error();
        } catch (Exception e) {
            e.printStackTrace();
            return SR.error();
        }
    }


    @ApiOperation("上传驾驶证背面")
    @PostMapping("/upload/license/back")
    public SR uploadLicenseBack(MultipartFile file, HttpServletRequest request) {
        String userIdByToken = JWTUtils.getUserIdByToken(request);
        User user = new User();
        user.setUserId(Integer.parseInt(userIdByToken));
        try {
            String url = OSSUtils.uploadFile(UUIDUtils.getUUID().toString(), "user/license/", file);
            user.setLicenseBack(url);   //更新驾驶证正面图片
            boolean result = userService.updateUser(user);
            return result ? SR.ok().data(url) : SR.error();
        } catch (Exception e) {
            e.printStackTrace();
            return SR.error();
        }
    }
//
//    @ApiOperation("添加驾驶证")
//    @PostMapping("license/front-back")
//    public SR addDriverLicense(@RequestBody AddDriverLicenseDTO addDriverLicenseDTO,HttpServletRequest request){
//        String userIdByToken = JWTUtils.getUserIdByToken(request);
//        User user = new User();
//        user.setUserId(Integer.parseInt(userIdByToken));
//        BeanUtils.copyProperties(addDriverLicenseDTO, user);
//        boolean b = userService.insertUserLicenseImg(user);
//        return b?SR.ok().message("添加驾驶证成功"):SR.error().message("添加驾驶证失败");
//    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{userId}")
    public SR delete(@PathVariable Integer userId) {
        boolean result = userService.delete(userId);
        return result ? SR.ok() : SR.error().message("删除失败");
    }


    //--------------------------不需要登录--------------------------
    @ApiOperation("上传头像")
    @PostMapping("/upload/avatar")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "文件", dataType = "file")})
    public SR uploadImg(MultipartFile file) {
        try {
            System.out.println(file);
            String url = OSSUtils.uploadFile(UUIDUtils.getUUID().toString(), "user/avatar/", file);
            return SR.ok().data(url);
        } catch (Exception e) {
            e.printStackTrace();
            return SR.error();
        }
    }

    @ApiOperation("注册用户")
    @PostMapping("register")
    public SR addUser(@RequestBody @ApiParam("用户对像") User user) {
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9])|(19[0-9]))\\d{8}$";
        String phone = user.getPhone();
        try {
            if (phone.length() != 11) {
                throw new Exception("您的手机号" + phone + "是错误格式！！！");
            } else {
                Pattern p = Pattern.compile(regex);
                Matcher m = p.matcher(phone);
                boolean isMatch = m.matches();
                if (!isMatch) {
                    throw new Exception("您的手机号" + phone + "是错误格式！！！");
                }
            }
            if (user == null || user.getUsername() == null || user.getPassword() == null) {
                return SR.error().message("用户名或密码不能为空");
            } else if (!userService.getUserByPhone(user.getPhone())) {
                throw new Exception("手机号已经被注册啦");
            }
            return userService.save(user) ? SR.ok() : SR.error();
        } catch (RepeatRegisterException e) {
            e.printStackTrace();
            return SR.error().message(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return SR.error().message(e.getMessage());
        }
    }
}
